var http = require('http')

var config = require('./config')
var controller = require('./controller')
var route = require('./route')

var routes = route.map(item => {
  let [module, fn] = item.impl.split('.')
  return {
    method: item.method,
    path: item.path,
    impl: item.impl,
    implFn: controller[module][fn]
  }
})

var server = http.createServer(function (req, res) {
  console.log(`客户端请求路径为：${req.url}`)

  //设置允许跨域的域名，*代表允许任意域名跨域
  res.setHeader("Access-Control-Allow-Origin", "*");
  //允许的header类型
  res.setHeader("Access-Control-Allow-Headers", "Content-type");
  //跨域允许的请求方式 
  res.setHeader("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");

  let method = req.method // 客户端请求方法
  let url = req.url

  let matchRoute = routes.find(item => {
    return item.method === method && item.path === url;
  })

  if (matchRoute) {
    matchRoute.implFn(req, res);
    return;
  }

  res.statusCode = 404;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Not Found');
})


server.listen(config.port, config.hostname, function () {
  console.log(`Server running at http://${config.hostname}:${config.port}/`)
})
